package com.example.imtoken.modules.main.wallet.create

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.R
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.logic.repository.WalletRepository
import com.example.imtoken.entitys.http.CoinsEntity
import com.example.imtoken.entitys.http.CreateEntityItem
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.AccountSchema
import com.example.imtoken.room.schema.WalletCheckedSchema
import kotlinx.coroutines.launch

class CreateWalletViewModel(private val repository: WalletRepository) : BaseViewModel() {

    val walletName = MutableLiveData<String>()
    val walletPass = MutableLiveData<String>()
    val walletPass1 = MutableLiveData<String>()
    val walletTips = MutableLiveData<String>()

    var createEntity: CreateEntityItem? = null

    val isSubmit = MutableLiveData(false)

    val isCreateSuccess = MutableLiveData(false)

    var _walletName: String? = null
        set(value) {
            field = value
            inspectEditText()
        }
    var _walletPass: String? = null
        set(value) {
            field = value
            inspectEditText()
        }
    var _walletPass1: String? = null
        set(value) {
            field = value
            inspectEditText()
        }

    private fun inspectEditText() {
        isSubmit.value =
            _walletName?.length ?: 0 > 0 && _walletPass?.length ?: 0 > 0 && _walletPass1?.length ?: 0 > 0
    }

    fun onCreateWallet(coin: String?) {
        if (isSubmit.value == true) {
            if (walletPass.value != walletPass1.value) {
                mErrorResId.value = R.string.createUserTips_pass
                return
            }
            mDialog.value = true

            viewModelScope.launch {
                try {
                    createEntity = repository.createUser(
                        coin ?: "eth",
                        walletPass.value,
                        walletName.value,
                        walletTips.value
                    )[0]
                    addAccountData()
                    val coins = repository.getCoins(createEntity?.coin?.coin ?: "eth")
                    addWalletChecked(coins, coin)

                    App.appCode?.let { code ->
                        val bindingWallet = repository.bindingWallet(
                            createEntity?.coin?.address,
                            walletPass.value,
                            coin ?: "eth",
                            code
                        )
                        bindingWallet?.let { LogUtils.json(it) }
                    }

                    mDialog.value = false
                    isCreateSuccess.value = true

                } catch (e: Exception) {
                    mDialog.value = false
                    mErrorStr.value = e.message
                }
            }

//            RetrofitUtils.apiService?.walletCreate(
//                coin,
//                walletPass.value,
//                walletName.value,
//                walletTips.value
//            )
//                ?.flatMap(Function<ResponseEntity<CreateEntity>, Observable<ResponseEntity<CoinsEntity>>> {
//                    if (it.code == 0) {
//                        createEntity = it.data?.get(0)
//                        addAccountData()
//                        return@Function RetrofitUtils.apiService?.coins(createEntity?.coin?.coin)
//                    } else {
//                        mDialog.postValue(false)
//                        return@Function Observable.error {
//                            ApiException(it.msg)
//                        }
//                    }
//                })?.subscribeOn(Schedulers.io())
//                ?.observeOn(Schedulers.io())
//                ?.subscribe(object : BaseObserver<ResponseEntity<CoinsEntity>>() {
//                    override fun onSuccess(value: ResponseEntity<CoinsEntity>) {
//                        mDialog.postValue(false)
//                        if (value.code == 0) {
//                            addWalletChecked(value.data, coin)
//
//                            isCreateSuccess.postValue(true)
//                        } else {
//                            mErrorStr.postValue(value.msg)
//                        }
//                    }
//
//                    override fun onFailed(e: Throwable) {
//                        mDialog.postValue(false)
//                    }
//
//                })
        }
    }

    private fun addAccountData() {
        val account = AccountSchema(
            null,
            walletPass.value,
            walletTips.value,
            createEntity?.token,
            createEntity?.coin?.address,
            createEntity?.coin?.coin,
            createEntity?.coin?.mnemonic,
            createEntity?.coin?.public_key,
            walletName.value,
            2
        )
        if (AppDataBase.instance.getAccountDao().insertAccount(account) > 0) {
            LogUtils.e("钱包账号添加成功")
            App.newCreateData = createEntity
        } else {
            LogUtils.e("钱包账号添加失败")
        }
    }

    fun addWalletChecked(coinsEntity: CoinsEntity?, coin: String?) {
        coinsEntity?.let {
            it.forEach { item ->
                if (item.coin == coin) {
                    val walletCheckedSchema = WalletCheckedSchema(
                        item.icon,
                        item.coin,
                        item.name,
                        createEntity?.coin?.address,
                        item.describe
                    )
                    if (AppDataBase.instance.getWalletCheckedDao()
                            .insertWalletChecked(walletCheckedSchema) > 0
                    ) {
                        LogUtils.e("添加选择-${item.coin}-成功")
                    } else {
                        LogUtils.e("添加选择-${item.coin}-失败")
                    }
                }
            }
        }
    }

}